/*
 * Created on 2005-10-17
 *
 */
package com.yl.cap.analyst.work.service;

import jaoso.framework.domain.Role;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.faquir.hibernate.queryhelper.Page;
import org.quartz.Trigger;

import com.yl.cap.analyst.config.ContextBean;
import com.yl.cap.analyst.report.helper.operator.Operator;
import com.yl.cap.analyst.work.dao.JobTaskDAO;
import com.yl.cap.analyst.work.domain.JobLog;
import com.yl.cap.analyst.work.domain.TriggerCollection;
import com.yl.cap.analyst.work.job.CreateReportThread;
import com.yl.cap.analyst.work.task.CreateReportTask;
import com.yl.cap.analyst.work.task.Task;

public class WorkServiceImpl implements WorkService
{
    private JobTaskDAO jobTaskDAO;

    private TriggerCollection triggerCollection;

    private ContextBean contextBean;

    public static List xmlFileNames = new ArrayList();

    private Operator operator;

    /**
     * @return Returns the contextBean.
     */
    public ContextBean getContextBean()
    {
        return contextBean;
    }

    /**
     * @param contextBean
     *            The contextBean to set.
     */
    public void setContextBean(ContextBean contextBean)
    {
        this.contextBean = contextBean;
    }

    /**
     * @return Returns the jobTaskDAO.
     */
    public JobTaskDAO getJobTaskDAO()
    {
        return jobTaskDAO;
    }

    /**
     * @param jobTaskDAO
     *            The jobTaskDAO to set.
     */
    public void setJobTaskDAO(JobTaskDAO jobTaskDAO)
    {
        this.jobTaskDAO = jobTaskDAO;
    }

    /**
     * @return Returns the tigerCollection.
     */
    public TriggerCollection getTriggerCollection()
    {
        return triggerCollection;
    }

    /**
     * @param tigerCollection
     *            The tigerCollection to set.
     */
    public void setTriggerCollection(TriggerCollection tigerCollection)
    {
        this.triggerCollection = tigerCollection;
    }

    public List searchTask(String groupId)
    {
        Role r = (Role) jobTaskDAO.loadEntity(Role.class, groupId);
        String groupName = r.getDesc();

        String jobRoot = ContextBean.rootPath + "conf"
                + File.separator + "task";
        File taskDir = new File(jobRoot);
        File[] taskFiles = taskDir.listFiles();
        List retFiles = new ArrayList();
        for (int i = 0; i < taskFiles.length; i++)
        {
            if (!xmlFileNames.contains(jobRoot+File.separator+taskFiles[i].getName()))
            {
                if (operator.isAccess(jobRoot+File.separator+taskFiles[i].getName(), groupName))
                {
                    retFiles.add(taskFiles[i]);
                }
            }
        }
        return retFiles;
    }

    public void addTask(String taskFileName) throws Exception
    {
        xmlFileNames.add(taskFileName);

        File taskFile = new File(taskFileName);
        byte[] byteFile = new byte[(int) taskFile.length()];
        FileInputStream fis = new FileInputStream(taskFile);
        fis.read(byteFile);
        String strFile = new String(byteFile);
        int posF = strFile.indexOf("task type=\"");
        int posB = strFile.indexOf("\"", posF + 11);
        String type = strFile.substring(posF + 11, posB);
        posF = strFile.indexOf("tiger=\"", posB);
        posB = strFile.indexOf("\"", posF + 7);
        String tigerName = strFile.substring(posF + 7, posB);
        fis.close();
        Task task = null;
        if ("CreateReport".equals(type))
        {
            task = new CreateReportTask();
            task.setTaskFileName(taskFileName);
        }
        if (TriggerCollection.jobMap == null)
        {
            TriggerCollection.jobMap = new HashMap();
        }
        Map jobMap = TriggerCollection.jobMap;
        if (jobMap.get(tigerName) == null)
        {
            jobMap.put(tigerName, new ArrayList());
        }
        List jobList = (List) jobMap.get(tigerName);

        jobList.add(task);
    }

    public List getAllTrigger()
    {
        List retList = new ArrayList();
        List list = triggerCollection.getTigerList();
        for (int i = 0; i < list.size(); i++)
        {
            retList.add(((Trigger) list.get(i)).getName());
        }
        return retList;
    }

    public List getTaskByTiger(String tigerName)
    {
        return (List) TriggerCollection.jobMap.get(tigerName);
    }

    public void setTrigger(String taskFileName, String oldTigerName,
            String newTigerName)
    {
        Map tigerMap = TriggerCollection.jobMap;
        List taskList = (List) tigerMap.get(oldTigerName);
        Task task = null;
        for (int i = 0; i < taskList.size(); i++)
        {
            if (((Task) taskList.get(i)).getTaskFileName().equals(taskFileName))
            {
                task = (Task) taskList.get(i);
                taskList.remove(i);
                break;
            }
        }
        taskList = (List) tigerMap.get(newTigerName);
        taskList.add(task);
    }

    public void delTask(String tigerName, String taskFileName)
    {
        Map tigerMap = TriggerCollection.jobMap;
        List taskList = (List) tigerMap.get(tigerName);
        for (int i = 0; i < taskList.size(); i++)
        {
            if (((Task) taskList.get(i)).getTaskFileName().equals(taskFileName))
            {
                taskList.remove(i);
                xmlFileNames.remove(taskFileName);
                File file = new File(taskFileName);
                file.delete();
                break;
            }
        }
    }

    public void reOrderTask(String tigerName, List taskList)
    {
        Map tigerMap = TriggerCollection.jobMap;
        List oldTaskList = (List) tigerMap.get(tigerName);
        List newTaskList = new ArrayList();
        for (int i = 0; i < taskList.size(); i++)
        {
            for (int j = 0; j < oldTaskList.size(); j++)
            {
                if (((Task) oldTaskList.get(j)).getTaskFileName().equals(
                        taskList.get(i)))
                {
                    newTaskList.add(oldTaskList.get(j));
                    break;
                }
            }
        }
        tigerMap.put(tigerName, newTaskList);
    }
    public Boolean getTriggerState(String triggerName)
    {
        List triggerList = triggerCollection.getTigerList();
        Trigger trigger = null;
        for (int i = 0; i < triggerList.size(); i++)
        {
            trigger = (Trigger) triggerList.get(i);
            if (trigger.getName().equals(triggerName))
            {
                return (Boolean)triggerCollection.getTigerState().get(i);
            }
        }
        return new Boolean(false);
    }

    private void setTriggerState(String triggerName, Boolean state)
    {
        List triggerList = triggerCollection.getTigerList();
        Trigger trigger = null;
        for (int i = 0; i < triggerList.size(); i++)
        {
            trigger = (Trigger) triggerList.get(i);
            if (trigger.getName().equals(triggerName))
            {
                triggerCollection.getTigerState().set(i, state);
                break;
            }
        }
    }

    public void enableTrigger(String triggerName)
    {
        setTriggerState(triggerName, new Boolean(true));
    }

    public void disableTrigger(String triggerName)
    {
        setTriggerState(triggerName, new Boolean(false));
    }

    public void enableTrigger(int triggerNum)
    {
        triggerCollection.getTigerState().set(triggerNum, new Boolean(true));
    }

    public void disableTrigger(int triggerNum)
    {
        triggerCollection.getTigerState().set(triggerNum, new Boolean(false));
    }

    public void executeJob(String triggerName)
    {
        CreateReportThread t = new CreateReportThread();
        t.setTriggerName(triggerName);
        new Thread(t).start();
    }

    public List getTriggerState()
    {
        return triggerCollection.getTigerState();
    }

    public List getAllJobName()
    {
        return jobTaskDAO.getAllJobName();
    }

    public List getTaskByJob(String jobId)
    {
        JobLog log = (JobLog) jobTaskDAO.loadEntity(JobLog.class, jobId);
        return log.getTaskLog();
    }

    public Page getJob(String jobName, Date from, Date to, int currentPage)
            throws Exception
    {
        int pageSize = Integer.parseInt((String) contextBean.getConfigMap()
                .get("PageSize"));
        return jobTaskDAO.getJobByNameDate(jobName, from, to, currentPage,
                pageSize);
    }

    public Page getLastLog(int currentPage) throws Exception
    {
        int pageSize = Integer.parseInt((String) contextBean.getConfigMap()
                .get("PageSize"));
        return jobTaskDAO.getLastLog(currentPage, pageSize);
    }

    /**
     * @return Returns the operator.
     */
    public Operator getOperator()
    {
        return operator;
    }

    /**
     * @param operator
     *            The operator to set.
     */
    public void setOperator(Operator operator)
    {
        this.operator = operator;
    }
}
